package likou;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * @author: 唐小尊
 * @email: 1171702529@qq.com
 * @cate: 2021/07/18 20:01
 */
public class LRUCache {
    Map<Integer, int[]> map = new HashMap<>();
    LinkedList<Integer> list = new LinkedList<>();
    int maxSize;

    public LRUCache(int capacity) {
        maxSize = capacity;
    }

    public int get(int key) {
        if (map.containsKey(key)) {
            int[] now = map.get(key);
            int val = now[0];
            int index = now[1];
            now[1] = 0;
            map.put(key, now);
            for (; index < list.size(); index++) {
                if (list.get(index) == val) break;
            }
            list.remove(index);
            list.addFirst(val);
            return val;
        }
        return -1;
    }

    public void put(int key, int value) {
        if (list.size() == maxSize) {
            map.remove(list.getLast());
            list.removeLast();
        }
        map.put(key, new int[]{value, 0});
        list.addFirst(value);
    }
}
